import React from 'react';
import {Button, Icon, Upload} from 'antd';


class FileUpload extends React.Component {
    constructor(props){
       super(props);
    }

    handleChange = (info) => {
      const { limit } = this.props;
        let fileList = info.fileList;
    
        // 1. Limit the number of uploaded files
        //    Only to show two recent uploaded files, and old ones will be replaced by the new
        fileList = fileList.slice(-limit || -1);
    
        // 2. read from response and show file link
        fileList = fileList.map((file) => {
          if (file.response) {
            // Component will show file.url as link
            file.url = file.response.url;
          }
          const { response, url, name, uid } = file;
          return { response, url, name, uid };
        });
    
        // 3. filter successfully uploaded files according to response from server
        fileList = fileList.filter((file) => {
          if (file.response) {
            return file.response.status === 'success';
          }
          return true;
        });
        this.props.onFileUpload(fileList);
      }
    
    render() {
        const configs = {
            action: '/api/upload',
            onChange: this.handleChange,
            multiple: true,
            };
        return (
            <Upload {...configs} fileList={this.props.fileList}>
                <Button>
                <Icon type="upload" /> upload
                </Button>
            </Upload>
        )
  }
}

export default FileUpload;